<script setup>
import { ref, reactive, watchEffect } from 'vue'
import { listDept } from '@/api/system/dept'
import { getPurchaseOrderEchoBySupplierAPI } from '@/api/order/purchase/order'
import { Search } from '@element-plus/icons-vue'
const { proxy } = getCurrentInstance()
const props = defineProps({
  data: {
    type: Object,
    default: () => {}
  }
})

// 封装 方法 字典查询
const {
  quality_standard // 质量标准
} = proxy.useDict('quality_standard')

const emit = defineEmits(['cancel', 'submit'])

const ruleFormRef = ref(null)

const selection = ref([])
const deptOptions = ref([])

const TableData = ref([])

const supplierIsShow = ref(false)

// 新增字段
const ruleForm = reactive({
  purchaseContractNo: '', //采购合同编号
  firstBatchTime: '', // 首批到货时间
  endBatchTime: '', // 末批到货时间
  estimatedTime: '', //到货时间
  remark: '', // 备注
  enclosureUrl: '', // 附件
  actualUnitPrice: '', // 实际单价
  actualWeight: '', // 实际数量
  supplierId: '', // 供应商id
  materialList: []
})

/**
 * 列表枚举
 */
const column = ref([
  {
    label: '物料编码',
    prop: 'materialCode'
  },
  {
    label: '物料名称',
    prop: 'materialName'
  },
  {
    label: '规格型号',
    prop: 'specType',
    width: '220'
  },
  {
    label: '下达数量',
    prop: 'lowerWeight'
  },
  {
    label: '实际数量',
    prop: 'actualWeight',
    width: '200'
  },
  {
    label: '单位',
    prop: 'unitDict',
    width: '120'
  },
  {
    label: '实际单价',
    prop: 'actualUnitPrice',
    width: '200'
  },
  {
    label: '含税单价',
    prop: 'taxIncludedPrice',
    width: '200'
  },
  {
    label: '增值税税率',
    prop: 'invoiceTaxRate',
    width: '200'
  },
  {
    label: '操作',
    prop: 'x',
    width: '120'
  }
])

const rules = reactive({
  // purchaseContractNo: [{ required: true, message: '请填写采购合同编号', trigger: 'burl' }],
  // firstBatchTime: [{ required: true, message: '请填写首批到货时间', trigger: 'change' }],
  // endBatchTime: [{ required: true, message: '请填写末批到货时间', trigger: 'change' }],
  // estimatedTime: [{ required: true, message: '请填写到货时间', trigger: 'change' }],
  // enclosureUrl: [{ required: true, message: '请上传附件', trigger: 'change' }],
  supplierName: [{ required: true, message: '请选择供应商', trigger: 'blur' }]
  // demandDept: [{ required: true, message: '请选择需求部门', trigger: 'change' }],
  // reviewComments: [{ required: true, message: '请填写评审意见', trigger: 'burl' }]
})

/**
 * 存储点击的哪一行数据
 */
const rowForm = reactive({})

/**
 * 供应商弹窗
 * @param val
 */
const isSupplier = () => {
  supplierIsShow.value = true
}

// 供应商选择
const preservation = async val => {
  ruleForm.supplierName = val.supplierName
  ruleForm.supplierId = val.id
  supplierIsShow.value = false
  const res = await getPurchaseOrderEchoBySupplierAPI({
    idStr: ruleForm.idStr.join(','),
    supplierId: ruleForm.supplierId
  })
  ruleForm.materialList = res.data.materialList
}

// 提交
const submit = () => {
  return new Promise((resolve, reject) => {
    ruleFormRef.value.validate((valid, fields) => {
      if (!valid) {
        resolve(false)
        proxy.Mes('warning', '请填写完整')
        return
      }
      // 校验是否填写计划量和仓库
      const isif = ruleForm.materialList.some(item => !item.actualWeight || !item.actualUnitPrice)
      if (isif) {
        proxy.warningMsg('实际数量、实际单价必填！')
        return false
      }

      resolve(ruleForm)
    })
  })
}

// 文件
const uploadChange = url => {
  ruleForm.enclosureUrl = url
}

//输入实际单价时计算实际单价
const actualCalculate = record => {
  // 处理增值税税率为空或无效的情况，默认为 0
  const taxRate = Number(record.invoiceTaxRate) || 0
  // 如果增值税税率为 0，实际单价和含税单价应当相等
  if (taxRate === 0) {
    // 含税单价 = 实际单价
    record.taxIncludedPrice = Number(record.actualUnitPrice).toFixed(6)
  } else {
    // 含税单价 = 实际单价 + (实际单价 * 增值税税率)
    record.taxIncludedPrice = customFixed(
      Number(record.actualUnitPrice) + Number(record.actualUnitPrice) * (taxRate / 100),
      6
    )
  }
}

//输入含税单价时计算实际单价
const taxInclCalculate = record => {
  // 处理增值税税率为空或无效的情况，默认为 0
  const taxRate = Number(record.invoiceTaxRate) || 0
  // 如果增值税税率为 0，实际单价和含税单价应当相等
  if (taxRate === 0) {
    // 含税单价 = 实际单价
    record.actualUnitPrice = Number(record.taxIncludedPrice).toFixed(6)
  } else {
    // 含税单价/(增值税率/100+1)
    record.actualUnitPrice = customFixed(Number(record.taxIncludedPrice) / (1 + taxRate / 100), 6)
    //   (
    //   Number(record.taxIncludedPrice) -
    //   Number(record.taxIncludedPrice) * (taxRate / 100)
    // ).toFixed(6)
  }
}

/**
 * 计算-单价输入
 */
const calculate = record => {
  // 处理增值税税率为空或无效的情况，默认为 0
  const taxRate = Number(record.invoiceTaxRate) || 0

  // 如果增值税税率为 0，实际单价和含税单价应当相等
  if (taxRate === 0) {
    // 含税单价 = 实际单价
    record.taxIncludedPrice = Number(record.actualUnitPrice).toFixed(6)
  } else {
    // 含税单价 = 实际单价 + (实际单价 * 增值税税率)
    record.taxIncludedPrice = customFixed(
      Number(record.actualUnitPrice) + Number(record.actualUnitPrice) * (taxRate / 100),
      6
    )
  }
}

/**
 * 不进行四舍五入且保留小数
 * @param value
 * @param decimalPlaces
 */
function customFixed(value, decimalPlaces) {
  const factor = Math.pow(10, decimalPlaces)
  return Math.floor(value * factor) / factor
}

/**
 * 填入
 */
const fillIn = () => {
  if (!ruleForm.actualUnitPrice) return proxy.warningMsg('请先输入税率!')
  ruleForm.materialList.forEach(item => {
    item.invoiceTaxRate = ruleForm.actualUnitPrice
    calculate(item)
  })
}

/**
 * 删除
 */
const remove = record => {
  const index = ruleForm.materialList.findIndex(item => item.orderId == record.orderId)
  ruleForm.materialList.splice(index, 1)
}

watchEffect(() => {
  if (props.data?.id) {
    for (let key in props.data) {
      ruleForm[key] = props.data[key]
    }
  }
  ruleForm.materialList = props.data.materialList
  ruleForm.estimatedTime = props.data.estimatedTime
  ruleForm.idStr = props.data.idStr
})

function handleAdd(row) {
  listDept().then(response => {
    deptOptions.value = proxy.handleTree(response.data, 'deptId')
  })
  if (row != undefined) {
    ruleForm.demandDept = row.deptId
  }
}
handleAdd()
defineExpose({ submit })
</script>

<template>
  <div class="app-container">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-position="right"
      inline
      scroll-to-error
      label-width="120px"
    >
      <el-form-item label="采购合同编号">
        <el-input clearable v-model="ruleForm.purchaseContractNo" />
      </el-form-item>
      <!-- <el-form-item label="供应商信息" prop="supplierName">
        <el-input clearable @click="supplierIsShow = true" v-model="ruleForm.supplierName" />
      </el-form-item> -->
      <el-form-item label="首批到货时间">
        <el-date-picker
          v-model="ruleForm.firstBatchTime"
          type="datetime"
          placeholder="请选择时间"
          format="YYYY/MM/DD hh:mm:ss"
          value-format="YYYY-MM-DD hh:mm:ss"
        />
      </el-form-item>
      <el-form-item label="末批到货时间">
        <el-date-picker
          v-model="ruleForm.endBatchTime"
          type="datetime"
          placeholder="请选择时间"
          format="YYYY/MM/DD hh:mm:ss"
          value-format="YYYY-MM-DD hh:mm:ss"
        />
      </el-form-item>
      <el-form-item label="预计到货时间">
        <el-date-picker
          v-model="ruleForm.estimatedTime"
          type="datetime"
          placeholder="请选择时间"
          format="YYYY/MM/DD hh:mm:ss"
          value-format="YYYY-MM-DD hh:mm:ss"
        />
      </el-form-item>
      <el-form-item label="供应商" prop="supplierName">
        <el-input clearable @click="isSupplier" v-model="ruleForm.supplierName" />
      </el-form-item>
      <div class="rk">
        <el-form-item label="备注">
          <el-input
            clearable
            v-model="ruleForm.remark"
            :rows="3"
            type="textarea"
            placeholder="请输入备注"
            :input-style="{ width: '100%' }"
          />
        </el-form-item>
      </div>

      <div>
        <el-form-item label="上传附件">
          <FileUpload v-model="ruleForm.enclosureUrl" v-if="ruleForm.enclosureUrl" />
          <DownloadFile :fileList="ruleForm.enclosureUrl" v-else />
        </el-form-item>
      </div>
      <div class="fillIn">
        <el-form-item label="税率">
          <div class="fillIn-box">
            <el-input type="number" v-model="ruleForm.actualUnitPrice" clearable></el-input>
            <el-button type="warning" @click="fillIn">填入</el-button>
          </div>
        </el-form-item>
      </div>
    </el-form>
    <p-table keyId="materialId" :loading="loading" :data="ruleForm.materialList" :column="column">
      <template #columnCell="{ column, record }">
        <el-input-number v-model="record.actualWeight" v-if="column.label == '实际数量'" min="0" clearable />
        <el-input
          type="number"
          v-model="record.actualUnitPrice"
          v-if="column.label == '实际单价'"
          min="0"
          clearable
          @change="actualCalculate(record)"
        />
        <el-input
          type="number"
          v-model="record.taxIncludedPrice"
          v-if="column.label == '含税单价'"
          min="0"
          clearable
          @change="taxInclCalculate(record)"
        />
        <el-input
          type="number"
          v-model="record.invoiceTaxRate"
          v-if="column.label == '增值税税率'"
          :min="0"
          clearable
          @change="calculate(record)"
        />
        <!-- 操作 -->
        <div v-if="column.prop == 'x'">
          <el-link type="danger" @click="remove(record)">删除 </el-link>
        </div>
      </template>
    </p-table>

    <Supplier :is-show="supplierIsShow" @preservation="preservation" @cancel="supplierIsShow = false" />
  </div>
</template>

<style lang="scss" scoped>
.btn {
  margin-top: 20px;
}

.rk ::v-deep .el-form-item {
  width: 100% !important;
}
.fillIn {
  float: right;
  .fillIn-box {
    display: flex;
    align-items: center;
  }
}
</style>
